package com.linkage.jz.bankruptcy.activity.Main;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.fragment.Main.DateCalcDateFrgment;
import com.linkage.jz.bankruptcy.fragment.Main.DateCalcDaysFrgment;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * A login screen that offers login via email/password.
 */
public  class PenaltyCalcActivity extends BaseActivity implements OnClickListener{
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private ShapeLoadingDialog shapeLoadingDialog ;
    int date_type =1;
    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

        top_back.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("违约金计算器");
        top_mune.setVisibility(View.INVISIBLE);
    }




    TextView top_title,tv_stime,tv_etime,tv_type,calc_ret,calc_ret2,calc_ret3,calc_ret_day,item_other3;
    Button top_back,top_mune,btn_calc,btn_reset;
    RelativeLayout rl_money,re_stime,re_etime,re_type,rl_rate;
    EditText item_money,item_rate;
    LinearLayout showrate,ll_calc_ret;
    private  View view_other3 ;
    @Override
    public void initView() {
        //登录层、下拉层、其它登录方式层

        top_mune = findViewById(R.id.top_mune);

        top_back = findViewById(R.id.top_back);
        top_title = findViewById(R.id.top_title);
        calc_ret = findViewById(R.id.calc_ret);
        calc_ret2 =findViewById(R.id.calc_ret2);
        calc_ret3 = findViewById(R.id.calc_ret3);
        calc_ret_day = findViewById(R.id.calc_ret_day);
        tv_stime = findViewById(R.id.tv_stime);
        tv_etime = findViewById(R.id.tv_etime);
        tv_type = findViewById(R.id.tv_type);
        btn_calc = findViewById(R.id.btn_calc);
        rl_money = findViewById(R.id.rl_money);
        re_stime = findViewById(R.id.re_stime);
        re_etime = findViewById(R.id.re_etime);
        re_type = findViewById(R.id.re_type);

        rl_rate = findViewById(R.id.rl_rate);
        item_money = findViewById(R.id.item_money);
        item_rate = findViewById(R.id.item_rate);
        ll_calc_ret = findViewById(R.id.ll_calc_ret);
        btn_reset =findViewById(R.id.btn_reset);
        item_other3 = findViewById(R.id.item_other3);
        view_other3 = findViewById(R.id.view_other3);
        btn_reset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                btn_reset.setVisibility(View.GONE);
                ll_calc_ret.setVisibility(View.GONE);
                tv_stime.setText("");
                tv_etime.setText("");
                item_rate.setText("");
                item_money.setText("");

                type = -1;
                tv_type.setText("");
                showSave();

            }
        });

        item_money  .addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        item_rate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        re_stime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                date_type = 1;
                if(tv_stime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_stime.getText().toString());
                }

            }
        });

        re_etime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                date_type = 2;
                if(tv_etime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_etime.getText().toString());
                }

            }
        });

        btn_calc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String sTime = tv_stime.getText().toString();
                String eTime = tv_etime.getText().toString();
                String rate = item_rate.getText().toString();
                String money = item_money.getText().toString();

//                if(type==-1)
//                {
//                    Toast.makeText(PenaltyCalcActivity.this,"请选择类型",Toast.LENGTH_LONG).show();
//                   return;
//                }
                if("".equalsIgnoreCase(money))
                {
                    Toast.makeText(PenaltyCalcActivity.this,"请填写金额",Toast.LENGTH_LONG).show();
                    return;
                }


                if("".equalsIgnoreCase(sTime))
                {
                    Toast.makeText(PenaltyCalcActivity.this,"请选择起算日期",Toast.LENGTH_LONG).show();
                    return;
                }

                if("".equalsIgnoreCase(eTime))
                {
                    Toast.makeText(PenaltyCalcActivity.this,"请选择截止日期",Toast.LENGTH_LONG).show();
                    return;
                }

                if(getTimeCompareSize(sTime,eTime) == 1)
                {
                    Toast.makeText(PenaltyCalcActivity.this,"截止日期不能早于起算日期",Toast.LENGTH_LONG).show();

                    return;
                }

                if("".equalsIgnoreCase(rate))
                {
                    Toast.makeText(PenaltyCalcActivity.this,"请填写违约金率",Toast.LENGTH_LONG).show();
                    return;
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                float f_rate = Float.parseFloat(rate)/100;
                float f_money = Float.parseFloat(money);

                if(type == 0)
                {
                    f_rate = f_rate/360;
                }else if (type==1)
                {
                    f_rate = f_rate/30;
                }

                try {

                   long getTimeDistance =  getTimeDistance(sdf.parse(sTime), sdf.parse(eTime));

                   float ret = f_money*f_rate* getTimeDistance;
                    String result = String .format("%.2f",ret);
//                   ret = (float)(ret * 100 )/100;
                    calc_ret.setText(sTime+"至"+eTime +" 共");
                    calc_ret_day.setText(""+getTimeDistance);
                    if(type == 0)
                    {
                        rate = rate+"%/年";
                    }
                    if(type == 1)
                    {
                        rate = rate+"%/月";
                    }

                    if(type == 2)
                    {
                        rate = rate+"%/天";
                    }

                    calc_ret3.setText(result);
                    calc_ret2.setText(rate);
                    btn_reset.setVisibility(View.VISIBLE);
                    ll_calc_ret.setVisibility(View.VISIBLE);
                }catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        });

        view_other3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final List<String> values = new ArrayList<String>();

                AlertDialog.Builder builder = new AlertDialog.Builder(PenaltyCalcActivity.this);

                //builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("请选择");
                //    指定下拉列表的显示数据
                final String[] cities = {"每逾期一年", "每逾期一月","每逾期一天",};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
//                        tv_type.setText(cities[which]);

                        if(which == 0)
                        {
                            item_other3.setText("/年");
                        }
                        if(which == 1)
                        {
                            item_other3.setText("/月");
                        }
                        if(which == 2)
                        {
                            item_other3.setText("/天");
                        }

                        type = which;
                        showSave();
                    }
                });
                builder.show();

            }
        });
        showSave();
    }

    private void showSave()
    {
        String str1 =  item_money.getText().toString().trim();
        String str2 =  tv_stime.getText().toString().trim();
        String str3 =  tv_etime.getText().toString().trim();

        String str5 =  item_rate.getText().toString().trim();


        if(!str1.equalsIgnoreCase("") &&  !str2.equalsIgnoreCase("")
                &&  !str3.equalsIgnoreCase("") && !str5.equalsIgnoreCase("")
                )


        {


                btn_calc.setClickable(true);
                btn_calc.setBackgroundResource((R.drawable.corner_btn));

        }else{
            btn_calc.setClickable(false);
            btn_calc.setBackgroundResource((R.drawable.corner_nosel_btn));
        }


    }


    public static void start(Context context) {
        Intent intent = new Intent(context, PenaltyCalcActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_calcpenalty);

        initView();
//        shapeLoadingDialog = new ShapeLoadingDialog(this);


        super.onCreate(savedInstanceState);
    }

    //初始化视图


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
                MainActivity.start(this);
                finish();
                break;
            case R.id.ll_phonelogin:
                PhoneLoginActivity.start(this);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.getPwd:
                GetPwdOneActivity.start(this);
            default:
                break;
        }
    }


    private int type =2;




    public void setDate(String initdata){

        //通过自定义控件AlertDialog实现
        AlertDialog.Builder builder = new AlertDialog.Builder(PenaltyCalcActivity.this);
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_dateshow, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);
        //初始化当前日期
        Calendar calendar = Calendar.getInstance();
        if("".equalsIgnoreCase(initdata)) {
            calendar.setTimeInMillis(System.currentTimeMillis());

        }else{
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date initdate = sdf.parse(initdata);
                calendar.setTime(initdate);
            }catch (Exception ex)
            {
                ex.printStackTrace();
            }

        }
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);
        //设置date布局
        builder.setView(view);
        builder.setTitle("设置日期信息");
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //日期格式
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
//                        oplandate.setText(sb);
//                        //赋值后面闹钟使用
                int mYear = datePicker.getYear();
                int mMonth = datePicker.getMonth();
                int mDay = datePicker.getDayOfMonth();
                if(date_type ==1)
                {
                    tv_stime.setText(sb.toString());
                }else{
                    tv_etime.setText(sb.toString());
                }
                showSave();
                dialog.cancel();
            }
        });
        builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }




    /**
     * 获得两个日期间距多少天
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public  long getTimeDistance(Date beginDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(beginDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, fromCalendar.getMinimum(Calendar.HOUR_OF_DAY));
        fromCalendar.set(Calendar.MINUTE, fromCalendar.getMinimum(Calendar.MINUTE));
        fromCalendar.set(Calendar.SECOND, fromCalendar.getMinimum(Calendar.SECOND));
        fromCalendar.set(Calendar.MILLISECOND, fromCalendar.getMinimum(Calendar.MILLISECOND));

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, fromCalendar.getMinimum(Calendar.HOUR_OF_DAY));
        toCalendar.set(Calendar.MINUTE, fromCalendar.getMinimum(Calendar.MINUTE));
        toCalendar.set(Calendar.SECOND, fromCalendar.getMinimum(Calendar.SECOND));
        toCalendar.set(Calendar.MILLISECOND, fromCalendar.getMinimum(Calendar.MILLISECOND));

        long dayDistance = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
        dayDistance = Math.abs(dayDistance);
//        calc_day.setText(dayDistance+"天");
        return dayDistance;
    }



    public static int getTimeCompareSize(String startTime, String endTime){
        int i=0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime()<date1.getTime()){
                i= 1;
            }else if (date2.getTime()==date1.getTime()){
                i= 2;
            }else if (date2.getTime()>date1.getTime()){
                //正常情况下的逻辑操作.
                i= 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  i;
    }


}


